package com.gxuwz.attend.web.servlet.admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Department;
import com.gxuwz.attend.service.admin.DepartmentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;
@WebServlet("/admin/departments")
public class DepartmentServlet extends HttpServlet {

    private DepartmentService departmentService;
    private final ObjectMapper objectMapper = new ObjectMapper();



    @Override
    public void init() throws ServletException {
        super.init();
        departmentService = AppContext.getBean(DepartmentService.class);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String id = request.getParameter("id");
        System.out.println(id);
        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        int offset = (page - 1) * size;

        List<Department> departments = departmentService.getAllDepartments(id,name, size, offset);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String json = objectMapper.writeValueAsString(departments);
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Department department = objectMapper.readValue(request.getInputStream(), Department.class);
        departmentService.addDepartment(department);
        response.setStatus(HttpServletResponse.SC_CREATED); // 201 Created
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Department department = objectMapper.readValue(request.getInputStream(), Department.class);
        System.out.println(department.getDepID());
        System.out.println(department.getDepName());
        System.out.println(department.getId());
        departmentService.updateDepartment(department);
        response.setStatus(HttpServletResponse.SC_OK); // 200 OK
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String depID = request.getParameter("depID");
        System.out.println(depID);
        departmentService.deleteDepartment(depID);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204 No Content
    }
}


